//
//  MyCommentViewController.m
//  Growth
//
//  Created by MEET on 12-1-5.
//  Copyright 2012 MEETStudio. All rights reserved.
//

#import "PersonalLetterViewController.h"
#import "ASIHTTPConnection.h"

@implementation PersonalLetterViewController

static WebConnectionArray *userLetter_connection;

static ASIHTTPConnection *privateLetter_connect;

@synthesize myTableView;

@synthesize MyLetterArray;

@synthesize userId;


// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    self.navigationItem.title = @"我的私信";
    
      self.userId=[[[NSUserDefaults standardUserDefaults] valueForKey:USER_ID] intValue];
   
    pageNo = 1;
	
	//table 下拉刷新
	if (_refreshHeaderView == nil) {
		
		_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - myTableView.bounds.size.height, self.view.frame.size.width, myTableView.bounds.size.height)];
		_refreshHeaderView.delegate = self;
		[myTableView addSubview:_refreshHeaderView];
		
		
	}
	
	//  update the last update date
	[_refreshHeaderView refreshLastUpdatedDate];
    
    [self.myTableView setContentOffset:CGPointMake(0,-66)];
    
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:self.myTableView];
    
    [self  loadLetterDataWith:[NSString stringWithFormat:@"%d",self.userId]];
    
    

    self.navigationController.title = @"我的私信";
    
    //定义返回按钮
    UIBarButtonItem * backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: @"返回" style:UIBarButtonSystemItemDone target:self action: nil];   
    
    [[self navigationItem] setBackBarButtonItem:backBarButtonItem];  
    [backBarButtonItem release]; 
    
    [super viewDidLoad];
}


#pragma mark  Load Data

- (void)loadLetterDataWith:(NSString *)userId{
    
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    NSString *UserID = [[NSUserDefaults standardUserDefaults] valueForKey:USER_ID];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/ListMessageInBox.aspx?UserID=%@&pageNo=%d",BASEURL,userName,UserID,pageNo];
	NSURL *url = [NSURL URLWithString:urlString];
    
    if (privateLetter_connect  != nil) {
        
        [privateLetter_connect release];
        privateLetter_connect = nil;
    }
    
    privateLetter_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:YES];
    privateLetter_connect.connectionDelegate = self;
    
    [privateLetter_connect startAsynchronous];
    

    
  	
}

- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
    
    
}

- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{
    
    CLog(@"letter dict = %@",dict);
    
    NSArray *array = [dict objectForKey:@"Records"];
    if (array != nil && array.count > 0) {
        
        if (MyLetterArray == nil) {
            MyLetterArray = [[NSMutableArray alloc]init];
        }
        if (pageNo == 1) {
            [MyLetterArray removeAllObjects];
        }
        
        [MyLetterArray addObjectsFromArray:array];
        [self.myTableView reloadData];
        
    }
    
}


#pragma mark -WebConnection delegate
 
- (void)connectionArraySuccess:(NSDictionary *)dict connectionURL:(NSString *)url{
    CLog(@"info %@",  dict);
    //    for (NSString *key in [dict allKeys]) {
    //        CLog(@"info %@",  dict);
    //       // [dict objectForKey:key]
    //    }
    
    [LoadingView hideWithAnimated:YES];
    if (dict==nil) {
        return;
    }
    
	if (self.MyLetterArray == nil) {
		self.MyLetterArray = [[NSMutableArray alloc] init];
	}
    else{
        [self.MyLetterArray removeAllObjects];
    }
	
	NSMutableArray *otherArray =[dict objectForKey:@"object"];///////////////////////////
    
	[self.MyLetterArray addObjectsFromArray:otherArray];
    
    CLog(@"MyLetterArray is %@!",MyLetterArray);
	[myTableView reloadData];
    
    CLog(@"content success!");
    
    if (MyLetterArray.count == 0) {
          [LoadingView showDurationMessageLoadingViewWith:10.0 message:@"您没有私信！" ];        
    }

    [self doneLoadingTableViewData];
    
}

- (void)connectionArrayError:(NSError *)error{
    [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误或超时！" duration:DEFAULT_LOADING_TIME *1.2];
    
    [self doneLoadingTableViewData];
 
}




#pragma mark UITableViewDataSource


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	
	//return 100;
    return self.MyLetterArray.count;
    
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	NSInteger row = [indexPath row];
	
	NSMutableDictionary *dict=[self.MyLetterArray objectAtIndex:row];
	
	static NSString *MyIdentifier = @"LetterTabelCell";
	// Try to retrieve from the table view a now-unused cell with the given identifier.
	LetterTabelCell *cell =(LetterTabelCell *) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
	
    if (cell == nil) {
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"LetterTabelCell" 
                                                     owner:self options:nil];
#ifdef __IPHONE_2_1
		cell = (LetterTabelCell *)[nib objectAtIndex:0];
#else
		cell = (LetterTabelCell *)[nib objectAtIndex:1];
#endif
        
	}
    
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	[cell loadCellWith:dict];
	
    
    return cell;
	
	
}



- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	
	
	return nil;
}


#pragma mark UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	
	UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
	return cell.frame.size.height;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	//	NSInteger row = [indexPath row];
	//	NSInteger section = [indexPath section];
	
	CLog(@"table cell did select!");
	
    //CLog(@"timelineId %@", self.userId);
   
    NSDictionary *dict = [MyLetterArray objectAtIndex:indexPath.row];
    NSString *threadId = [dict objectForKey:@"ThreadID"];
    
	LetterDetailViewController  *detailViewController = [[LetterDetailViewController alloc] initWithThreadId:threadId];
	
	[self.navigationController pushViewController:detailViewController animated:YES];  
    
    [detailViewController release];
   	
	return;
	
}




#pragma mark Pushview delegate


#pragma mark -
#pragma mark Table 下拉刷新
#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
    
    if (NETWORK_STATUS_UNLOADING) {
    
        [self loadLetterDataWith:[NSString stringWithFormat:@"%d",self.userId]];    
    }
    else{
        [self doneLoadingTableViewData];
        [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"哎呀，网络好像有问题！" duration:DEFAULT_LOADING_TIME *1.2];
    }

    
	_reloading = YES;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.myTableView];
	
}



#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
	
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1.0];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    if (privateLetter_connect != nil) {
        privateLetter_connect.connectionDelegate = nil;
        [privateLetter_connect release];
        privateLetter_connect = nil;
    }
    
    [myTableView release];
    
    [super dealloc];
}


-(IBAction)beforBackHome:(id)sender{
    if (self.delegate != nil) {
        [self.delegate setMenuControllerTapEnabel:YES];
    }
    [self backHome:nil];
}
@end
